<template>
  <view class="page">
    <view class="title-container">
      <input
        class="title"
        type="text"
        :placeholder="titlePlaceholder"
        placeholder-style="color: black;font-weight: bold;"
        v-model="titleValue"
        :maxlength="titleMaxLength"
      />
    </view>
    <view class="content-container">
      <textarea
        class="content"
        :placeholder="contentPlaceholder"
        placeholder-style="color: #6A6361;"
        v-model="contentValue"
        :maxlength="contentMaxLength"
      ></textarea>
    </view>
    <view class="image-container">
      <view v-show="imageSelected" class="image-show-box">
        <view class="image-delete-btn" @click="handleImageDelete">×</view>
        <image :src="imageSelected?.url" mode="aspectFill"></image>
      </view>
      <view
        class="image-select-btn"
        v-show="!imageSelected"
        @click="handleImageSelected"
      ></view>
    </view>
    <picker mode="selector" :range="tapListView" @change="handleTapSelected">
      <view class="tap-list-container">
        <view class="title">添加话题（选填）</view>
        <!-- <view class="tap-list">
          <view
            :class="{ tap: true, 'tap-selected': tapSelected === item.id }"
            v-for="item in tapList"
            @click="selectTap(item.id)"
            :key="item.id"
            >#{{ item.text }}</view
          >
        </view> -->
        <view class="tap-selected">{{ tapShowView }}</view>
      </view>
    </picker>
    <view class="btn-post-container">
      <view class="btn-post" @click="handlePost">发布动态</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { post } from "../../service/post";
import { imageUrl2DataUrl } from "../../utils/base64";

const props = defineProps({
  switchTabbar: {
    type: Function,
    default: () => {},
  },
});

const titleValue = ref("");
const contentValue = ref("");

const titleMaxLength = 100; // 标题最大长度
const contentMaxLength = 5000; // 内容最大长度

const titlePlaceholder = ref("标题");
const contentPlaceholder = ref("尽情倾诉吧~小树洞倾听您的烦恼");

// --- 处理话题选择 ---

const tapSelected = ref(null); // 选中的标签索引

const handleTapSelected = (e) => {
  const viewID = e.detail.value;
  if (viewID === "0") {
    tapSelected.value = null;
    return;
  }
  const selectId = tapList.value[viewID - 1].id; // 选择的标签ID
  tapSelected.value = selectId;
};

// 树洞类型标签
const tapList = ref([
  { id: 1, text: "", tc: "#CCC", bc: "#F2F2F2" },
  { id: 2, text: "", tc: "#CCC", bc: "#F2F2F2" },
  { id: 3, text: "", tc: "#CCC", bc: "#F2F2F2" },
  { id: 4, text: "", tc: "#CCC", bc: "#F2F2F2" },
  { id: 5, text: "", tc: "#CCC", bc: "#F2F2F2" },
  { id: 6, text: "", tc: "#CCC", bc: "#F2F2F2" },
]);

const tapListView = computed(() => {
  const result = tapList.value.map((item) => item.text);
  result.unshift("无");
  return result;
});

const tapShowView = computed(() => {
  const text = tapList.value.find(
    (item) => item.id === tapSelected.value
  )?.text;
  return text ? text : "无";
});

// --- 处理图片选择 ---
const imageSelected = ref(null); // 选中的图片

const handleImageSelected = () => {
  try {
    uni.chooseMedia({
      count: 1, // 选择图片的数量
      mediaType: ["image"], // 只选
      sourceType: ["album"], // 来源：相册
      sizeType: ["original", "compressed"], // 图片大小：原图和压缩图
      async success(res) {
        const imageUrl = res.tempFiles[0].tempFilePath;
        imageSelected.value = {};
        imageSelected.value.url = imageUrl; // 设置选中的图片
        const imageDataurl = await imageUrl2DataUrl(imageUrl); // 处理图片为base64 dataurl 格式
        imageSelected.value.dataurl = imageDataurl; // 设置图片的dataurl
      },
      fail(res) {
        throw new Error("选择图片失败", res);
      },
    });
  } catch (error) {
    console.error("选择图片时发生错误：", error);
  }
};

const handleImageDelete = () => {
  imageSelected.value = null; // 清除选中的图片
};

// --- 处理发布动态 ---

const clearForm = () => {
  titleValue.value = "";
  contentValue.value = "";
  tapSelected.value = null;
  imageSelected.value = null;
};

const handlePost = async () => {
  if (titleValue.value.trim() === "") {
    uni.showToast({
      title: "内容不能为空",
      icon: "none",
      duration: 2000,
    });
    return;
  }
  if (titleValue.value.trim().length > titleMaxLength) {
    uni.showToast({
      title: `标题长度不能超过${titleMaxLength}个字符`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  if (contentValue.value.trim() === "") {
    uni.showToast({
      title: "内容不能为空",
      icon: "none",
      duration: 2000,
    });
    return;
  }
  if (contentValue.value.trim().length > contentMaxLength) {
    uni.showToast({
      title: `内容长度不能超过${contentMaxLength}个字符`,
      icon: "none",
      duration: 2000,
    });
    return;
  }
  

  const postData = {
    title: titleValue.value.trim(),
    content: contentValue.value.trim(),
    tapId: +tapSelected.value ? tapSelected.value : null, // 如果没有选中标签，则为null
    imageUrl: imageSelected.value ? imageSelected.value.dataurl : null, // 如果有选中图片，则使用其dataurl
  }

  const res = await post.addPost(postData);
  if (res.success) {
    uni.showToast({
      title: "发布成功",
      icon: "success",
      duration: 2000,
    });
    clearForm(); // 清空表单
    // 跳转到首页
    props.switchTabbar({ active: "main" });
  }
}

onMounted(() => {
  // 获取所有帖子类型
  post.getPostType(tapList);
});
</script>

<style scoped lang="less">
.page {
  width: 100vw;
  min-height: 100vh;
  background-image: linear-gradient(to bottom, rgb(255, 212, 168), #fff);
  display: flex;
  flex-direction: column;
  padding-top: 20vw;
  padding-bottom: 25vw;

  .title-container {
    padding: 0 5vw;
    border-bottom: 1px solid #d3d3d3;

    .title {
      color: black;
      font-size: 5vw;
      font-weight: bold;
      padding: 2vw 0;
    }
  }

  .content-container {
    padding: 5vw;
    padding-bottom: 0;

    .content {
      width: 100%;
      height: 30vh;
    }
  }

  .image-container {
    display: flex;
    padding: 5vw;
    gap: 2vw;

    .image-show-box {
      position: relative;
      --size: 25vw;
      --radius: 2vw;
      width: var(--size);
      height: var(--size);
      border-radius: var(--radius);

      .image-delete-btn {
        position: absolute;
        top: 0;
        right: 0;
        width: 20%;
        height: 20%;
        background-color: #ff0000;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        transform: translate(20%, -20%);
        color: white;
        font-size: 4vw;
        line-height: 1;
      }

      image {
        width: 100%;
        height: 100%;
        border-radius: var(--radius);
      }
    }

    .image-select-btn {
      --size: 25vw;
      width: var(--size);
      height: var(--size);
      border-radius: 2vw;
      background-color: #f2f2f2;
      display: flex;
      justify-content: center;
      align-items: center;

      &[hidden] {
        display: none;
      }

      &::after {
        content: "+";
        color: #ccc;
        font-size: 9vw;
        font-weight: bold;
      }
    }
  }

  .tap-list-container {
    display: flex;
    justify-content: space-between;
    padding: 0 5vw;

    .title {
      font-size: 5vw;
      font-weight: bold;
    }

    // .tap-list {
    //   width: 100vw;
    //   height: 25vw;
    //   display: flex;
    //   flex-wrap: wrap;
    //   flex-direction: row;
    //   justify-content: space-evenly;
    //   align-items: center;
    //   align-content: center;
    //   gap: 3vw;

    //   .tap {
    //     --h: 7vw;
    //     width: 25vw;
    //     height: var(--h);
    //     text-align: center;
    //     line-height: var(--h);
    //     border-radius: 7vw;
    //     font-weight: 900;
    //     font-size: 4vw;
    //     color: #ccc;
    //     background-color: #f2f2f2;
    //   }
    // }
  }

  .btn-post-container {
    width: 100%;
    padding: 5vw;
    box-sizing: border-box;
    font-weight: bold;
    .btn-post {
      padding: 3vw;
      border-radius: 5vw;
      background-color: #d4e98c;
      text-align: center;
    }
  }
}
</style>
